package com.leetcode.partition1;

/**
 * @author `RKC`
 * @date 2021/10/23 14:32
 */
public class LC3无重复字符的最长子串 {

    public static int lengthOfLongestSubstring(String s) {
        if (s.length() == 0) return 0;
        return slidingWindow(s);
    }

    public static void main(String[] args) {
        String s = "pwwkew";
        System.out.println(lengthOfLongestSubstring(s));
    }

    private static int slidingWindow(String s) {
        int[] charTable = new int[128];
        int left = 0, right = 0, answer = 1;
        while (right < s.length()) {
            charTable[s.charAt(right)]++;
            if (charTable[s.charAt(right)] == 1) {
                //没有重复，可以加入窗口集合
                answer = Math.max(answer, right - left + 1);
            } else {
                //有重复的字符，左指针的字符退出，直到窗口内的没有重复为止
                while (!isNonRepeated(charTable)) {
                    charTable[s.charAt(left)]--;
                    left++;
                }
            }
            right++;
        }
        return answer;
    }

    private static boolean isNonRepeated(int[] charTable) {
        //检测哈希表中是否只含有0和1
        for (int i : charTable) {
            if (i > 1) return false;
        }
        return true;
    }
}
